package bhbt.taglib.pagetag;



import javax.servlet.ServletRequest;
import javax.servlet.jsp.tagext.TagSupport;

import bhbt.utils.StringUtil;







public class PageTag extends TagSupport {

    /**
     * 简单样式
     */
    private boolean simple;

    private String pageBeanName = Pagination.pageBeanName;

    private String formName = null;

    private String formAction = null;

    private Pagination retPagination = null;

    /**
     * 改变pageData对象时触发页面中的javaScript函数名称
     */
    private String functionName = null;


    private String width = "80%";

    /**
     * 方法名称: doStartTag 内容摘要: 重载标签库中的方法
     *
     * @return int 操作标志
     */
    public int doStartTag() {
        try {
            fillPageObject();
            String pageCode = "";
            boolean hasFunctionName = true;
            // 判断改变pageData对象时触发页面中的javaScript函数名称是否存在
            pageCode += getStyleCode();
            if (functionName == null) {
                pageCode += getScriptCode();
                hasFunctionName = false;
            }
            // javaScript方法名称
            String funName = null;
            // 判断是否存在改变pageData对象时触发页面中的javaScript函数名称
            if (hasFunctionName) {
                // 有则调用指定的javaScript方法
                // funName = functionName+"(this.value);";
                funName = functionName;
            } else {
                // 没有则以默认的方法调用javaScript方法
                // funName = "goPage(this.value);";
                funName = "goPage";
            }
            pageCode += getPageCode(retPagination, funName, hasFunctionName);
            // 将页面代码输出到标签所在的页面中
            pageContext.getOut().println(pageCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SKIP_BODY;
    }

    /**
     * 方法名称: fillPageObject 内容摘要: 填充分页对象
     *
     * @return boolean 返回操作成功标志
     */
    private boolean fillPageObject() {
        retPagination = new Pagination();
        Object pageBeanObj = pageContext.getAttribute(pageBeanName,pageContext.REQUEST_SCOPE);
        if (pageBeanObj instanceof Pagination) {
            // 获得分页对象
            retPagination = (Pagination) pageBeanObj;
            // 从页面上获取参数
            ServletRequest request = pageContext.getRequest();
            String pageStr = request.getParameter(pageBeanName+".page");
            String pageSizeStr = request.getParameter(pageBeanName+".pageSize");
            if(StringUtil.isNotBlank(pageStr) && StringUtil.isNotBlank(pageSizeStr)){
                retPagination.setPage(Integer.parseInt(pageStr));
                retPagination.setPageSize(Integer.parseInt(pageSizeStr));
                retPagination.setOrderBy(request.getParameter(pageBeanName+".orderBy"));
            }
        }
        return true;
    }

    private String getStyleCode(){
        StringBuffer sb = new StringBuffer("<style type='text/css'>");
        sb.append(".pagination{text-align:center; margin:0;font-size:15px;font-weight: bold;}");
        sb.append(".pagination select{display:none}");
        sb.append(".pagination ul{list-style-type:disc; margin:0;padding-left:1.5em; display:inline-block; border-radius:4px; }");
        sb.append(".pagination ul li{display:inline;}");
        sb.append(".pagination ul li a{color:#00CCCC; cursor:default; text-decoration:underline; float:left; padding:4px 12px; line-height:20px; text-decoration:none;  border-left-width:0;cursor:pointer;}");
        sb.append(".pagination ul li.first-child a{border-left-width:1px;border-bottom-left-radius:4px;border-top-left-radius:4px;cursor:pointer;}");
        sb.append(".pagination ul li.last-child a{border-top-right-radius:4px; border-bottom-right-radius:4px;cursor:pointer;}");
        sb.append(".pagination ul li.disabled a{color:#00CCCC; background-color:transparent;}");
        sb.append(".pagination ul li.active a:hover{cursor:pointer; }");
        sb.append("</style>");
        return sb.toString();
    }

    /**
     * 方法名称: getScriptCode 内容摘要: 获得标签中的JavaScript语句
     * @return String JavaScript语句
     */
    private String getScriptCode() {
        String javaScript = "<script type='text/javascript'>\n"
                + "function sort(colName){\n"
                + "var orderByObj=document.forms[" + formName + "]['" + pageBeanName + ".orderBy'];\n"
                + "if(orderByObj.value.toUpperCase().indexOf(colName.toUpperCase())>-1){\n"
                + "if(orderByObj.value.toUpperCase().indexOf(' DESC') > -1)orderByObj.value = colName+' ASC';"
                + "else orderByObj.value = colName+' DESC';}else{orderByObj.value = colName;}\n";
        if(formAction != null){
            javaScript += "document.forms[" + formName + "].action='"+formAction+"';\n";
        }
        javaScript += "document.forms[" + formName + "].submit();}\n";
        javaScript += "function goPage(thePage){\n"
                + "if(thePage!=undefined) document.forms["+formName+"]['"+pageBeanName+".page'].value=thePage;\n";
        if(formAction != null){
            javaScript += "document.forms[" + getFormName() + "].action='"+formAction+"'";
        }
        javaScript += "document.forms[" + getFormName() + "].submit();}\n";
        javaScript += "</script>";
        return javaScript;
    }

    /**
     * 方法名称: getPageCode 内容摘要: 获得页面中需要显示的代码
     *
     * @param pagination pagination
     * @param funName String 标签中的JavaScript方法名称
     * @param hasFunctionName 是否存在JavaScript方法名称
     * @return String 面中需要显示的代码
     */
    private String getPageCode(Pagination pagination, String funName, boolean hasFunctionName) {
        StringBuffer pageSb = new StringBuffer("<div class='pagination '>");
        if(0 == pagination.getTotalCount()){
            pageSb.append("<font color='#00CCCC'>未找到相关记录!</font>");
        }else {
            pageSb.append("<ul>");
            pageSb.append("<input type='hidden' name='"+pageBeanName+".orderBy' value='"+pagination.getOrderBy()+"'/>");
            pageSb.append("<input type='hidden' name='"+pageBeanName+".totalCount' value='"+pagination.getTotalCount()+"'/>");
            // 非简单样式
            if (!simple) {
                pageSb.append("<li class='first-child disabled'><a>");
                pageSb.append("第"+pagination.getPage()+"页/共"+pagination.getPageCount()+"页"+"&nbsp;&nbsp;共"+pagination.getTotalCount()+"条记录");
                pageSb.append("</a></li>");

            }
            String cls1 = pagination.getIsFirstPage()?"disabled":"active";
            String cls2 = pagination.getIsLastPage()?"disabled":"active";
            pageSb.append("<li class='"+cls1+"' title='首页' "+(pagination.getIsFirstPage()?"":"onclick='javascript:"+funName+"(1)'")+" ><a  "+(pagination.getIsFirstPage()?"":"href='javascript:"+funName+"(1)'")+">首页</a></li>");
            pageSb.append("<li class='"+cls1+"' title='上页' "+(pagination.getIsFirstPage()?"":"onclick='javascript:"+funName+"("+(pagination.getPage()-1)+")'")+"><a  "+(pagination.getIsFirstPage()?"":"href='javascript:"+funName+"("+(pagination.getPage()-1)+")'")+">上一页</a></li>");
            
            //当前页
            if (!simple) {
                pageSb.append("<li style='display:none;'><a><select  name='"+pageBeanName+".page' onchange=\""+funName+"(this.value);\">");
                for (int i = 1; i <= pagination.getPageCount(); i++) {
                    pageSb.append("<option value='"+i+"' "+(pagination.getPage()==i?"selected":"")+">"+i+"</option>");
                }
                pageSb.append("</select></a></li>");
                for (int i = 1; i <= pagination.getPageCount(); i++) {
                	
                	//当前页显示红色
                	if(pagination.getPage()==i){
                		pageSb.append("<li><a style = 'color:red;'>"+pagination.getPage()+"</a></li>");
                	}
                	//1+5>=6(大于的显示多6位)
                	else if(pagination.getPage()<i){
                		
                		if(pagination.getPage()+5>=i){
                			pageSb.append("<li onclick='javascript:"+funName+"("+i+")'><a href='javascript:"+funName+"("+i+")'>"+i+"</a></li>");
                		}
                		
                	}
                	//1+5>=6(小于的只显示3位)
                	else {
                		//7>1
                		if(pagination.getPage()-3<=i){
                			pageSb.append("<li onclick='javascript:"+funName+"("+i+")'><a href='javascript:"+funName+"("+i+")'>"+i+"</a></li>");
                		}
					}
	        			 
	        	 
                }
                
                
            }
            
            pageSb.append("<li class='"+cls2+"' title='下页' "+(pagination.getIsLastPage()?"":"onclick='javascript:"+funName+"("+(pagination.getPage()+1)+")'")+" ><a "+(pagination.getIsLastPage()?"":"href='javascript:"+funName+"("+(pagination.getPage()+1)+")'")+">下一页</a></li>");
            pageSb.append("<li class='"+cls2+"' title='末页' "+(pagination.getIsLastPage()?"":"onclick='javascript:"+funName+"("+pagination.getPageCount()+")'")+"><a "+(pagination.getIsLastPage()?"":"href='javascript:"+funName+"("+pagination.getPageCount()+")'")+">最后一页</a></li>");
            
            //每页多少行
//            
//            if(simple){
//                pageSb.append("<li><a><input type='text' name='"+pageBeanName+".page' size='2' style='height:17px'>");
//                pageSb.append("<span onclick='"+funName+"()'>GO</span></a></li>");
//            }else{
//                pageSb.append("<li class='last-child disabled'><a>");
//                pageSb.append("每页<select style='height:18px;' size='1' name='" + pageBeanName + ".pageSize' onchange=\"");
//                if(formAction != null){
//                    pageSb.append("document.forms['"+getFormName()+"'].action='"+formAction+"';");
//                }
//                pageSb.append("document.forms["+getFormName()+"].submit();\">");
//                int[] pageSizeArr = {10, 20, 40, 50};
//                for(int ps : pageSizeArr){
//                    pageSb.append("<option value='"+ps+"' "+(pagination.getPageSize()==ps?"selected":"")+">"+ps+"</option>");
//                }
//                pageSb.append("</select>行");
//                pageSb.append("</a></li>");
//            }
            pageSb.append("</ul>");
        }
        pageSb.append("</div>");
        return pageSb.toString();
    }

    private String getPageCode2(Pagination pagination, String funName, boolean hasFunctionName) {
        String pageCode = "<tr></tr><table cellspacing=\"0\" width='"+width+"'>\n"
                + "<tr><td style='border:1px solid #95b8e7; border-top:0; FONT-SIZE:12px; COLOR:#000; text-align:center; background:#d0e5f6' nowrap>\n"
                + "<input type=\"hidden\" name=\"" + pageBeanName + ".orderBy\" value=\""
                + pagination.getOrderBy() + "\">\n" + "<input type=\"hidden\" name=\"" + pageBeanName
                + ".totalCount\" value=\"" + pagination.getTotalCount() + "\">\n";
        if(0 == pagination.getTotalCount()){
            pageCode += "<div style='background:#FFF;text-align:center;'>未找到相关记录.</div>";
        }else{
            // 简单样式
            if (simple) {
                pageCode += "第<input type='text' name='" + pageBeanName + ".page" + "' value="
                        + pagination.getPage()
                        + " style='width:22px; height:16px' onkeypress='javascript:if(event.keyCode==13){" + funName
                        + "(this.value);}'>" + "<b>/</b>" + pagination.getPageCount() + "页";
            } else {
                pageCode += "第" + pagination.getPage() + "页/共" + pagination.getPageCount()
                        + "页" + "&nbsp;&nbsp;共" + pagination.getTotalCount() + "条记录&nbsp;&nbsp;每页\n"
                        + "<select size=\"1\" name=\"" + pageBeanName + ".pageSize\" "
                        + "style=\"border-bottom-style: solid\" onchange=\"";
                if(formAction != null){
                    pageCode += "document.forms[" + getFormName() + "].action='"+formAction+"';";
                }
                pageCode += "document.forms[" + getFormName() + "].submit();\">\n";
                pageCode += "<option value=\"10\" ";
                if (pagination.getPageSize() == 10) {
                    pageCode += "selected ";
                }
                pageCode += ">10</option>\n<option value=\"20\" ";
                if (pagination.getPageSize() == 20) {
                    pageCode += "selected ";
                }
                pageCode += ">20</option>\n<option value=\"40\" ";
                if (pagination.getPageSize() == 40) {
                    pageCode += "selected ";
                }
                pageCode += ">40</option>\n<option value=\"50\" ";
                if (pagination.getPageSize() == 50) {
                    pageCode += "selected ";
                }
                pageCode += ">50</option>\n</select>\n行&nbsp;&nbsp;<span>";
            }
            if (!pagination.getIsFirstPage()) {
                pageCode += "<a href=\"javascript:void(0)\"  onclick=\"" + funName + "(1)\" "
                        + "style=\"font-family:Webdings!important;color:#30ADE3;text-decoration:none;\" title='首页'> 9 </a></span>"
                        + "<a href=\"javascript:void(0)\" onclick=\"" + funName + "(" + (pagination.getPage() - 1)
                        + ")\" " + "style=\"font-family:Webdings!important;color:#30ADE3;text-decoration:none;\" title='上一页'> 7 </a>\n";
            } else {
                pageCode += "<font style=\"font-family:Webdings!important;color:000;\" title='首页'> 9 </font></span>"
                        + "<font style=\"font-family:Webdings!important;color:000;\" title='上一页'> 7 </font>\n";
            }
            // 页面选择页码下拉框
            if (!simple) {
                pageCode += "<select size=\"1\" name=\"" + pageBeanName + ".page\" "
                        + "style=\"border-bottom-style: solid\" onchange=\"" + funName + "(this.value);\">\n";
                String optionString = "";
                for (int i = 0; i < pagination.getPageCount(); i++) {
                    optionString += "<option value=\"" + (i + 1) + "\" ";
                    if (pagination.getPage() == i + 1) {
                        optionString += "selected ";
                    }
                    optionString += ">" + (i + 1) + "</option>\n";
                }
                pageCode += optionString;
                pageCode += "</select>";
            }
            if (!pagination.getIsLastPage()) {
                pageCode += "<a href=\"javascript:void(0)\" onclick=\"" + funName + "(" + (pagination.getPage() + 1)
                        + ")\" " + "style=\"font-family:Webdings!important;color:#30ADE3;text-decoration:none;\" title='下一页'> 8 </a>"
                        + "<a href=\"javascript:void(0)\" onclick=\"" + funName + "(" + pagination.getPageCount() + ")\" "
                        + "style=\"font-family:Webdings!important;color:#30ADE3;text-decoration:none;\" title='末页'> :</a>\n";
            } else {
                pageCode += "<font style=\"font-family:Webdings!important;color:000;\" title='下一页'> 8 </font></span>"
                        + "<font style=\"font-family:Webdings!important;color:000;\" title='末页'> :</font>\n";
            }
        }
        pageCode += "</td>\n</tr>\n</table>";
        return pageCode;
    }



    public boolean isSimple() {
        return simple;
    }
    public void setSimple(boolean simple) {
        this.simple = simple;
    }

    public String getFormName() {
        formName = StringUtil.isNotBlank(formName)?formName:"0";
        if(!"0".equals(formName) && !formName.startsWith("'")){
            formName += "'" + formName + "'";
        }
        return formName;
    }

    public void setFormName(String formName) {
        this.formName = formName;
    }

    public String getFormAction() {
        return formAction;
    }

    public void setFormAction(String formAction) {
        this.formAction = formAction;
    }

    public String getPageBeanName() {
        return pageBeanName;
    }

    public void setPageBeanName(String pageBeanName) {
        this.pageBeanName = pageBeanName;
    }

    public String getFunctionName() {
        return functionName;
    }

    public void setFunctionName(String functionName) {
        this.functionName = functionName;
    }

    public String getWidth() {
        return width;
    }
    public void setWidth(String width) {
        this.width = width;
    }


}
